// ##############################
// ####  note:  bokeweilai uart main fun
// ####  create:  TANWENHUI (twh:谭文辉)
// ####  date:   2024/6/18
// ##############################

#include "bkwl_common.h"
#include "dev_log.h"
#include "bkwl_event.h"
#include "bkwl_http.h"

bk_err_t bkwl_http_init(void)
{
	bk_err_t ret = BK_OK;

	return ret;
}

// bk_err_t bkwl_uart_close(void)
// {
// 	bk_err_t ret = BK_OK;
// 	int uart_id = 2;
// 	BK_LOG_ON_ERR(bk_uart_deinit(uart_id));
// 	return ret;
// }

// bk_err_t bkwl_http_upload_picture(char *url, char *picture_data, int picture_length)
// {
// 	bk_err_t ret = BK_OK;
// 	bk_http_input_t http_input;

// 	tprintf("bkwl_http_upload_picture entry\n");
// 	char *headers_base[] = {
// 		"Content-Type: image/jpeg",
// 		"Content-Length: %d", // 这里需要填写实际的图片长度
// 		NULL};

// 	char headers[100] = {0};
// 	sprintf(header, headers_base, picture_length);

// 	// 初始化 HTTP 请求结构体
// 	bk_http_input_init(&http_input);
// 	http_input.url = url;
// 	http_input.headers = headers;
// 	http_input.body = picture_data;
// 	http_input.body_length = picture_length;
// 	http_input.method = HTTP_METHOD_POST;

// 	// 发送 HTTP 请求
// 	bk_http_input(&http_input);

// 	// 清理工作
// 	bk_http_input_deinit(&http_input);
// 	tprintf("bkwl_http_upload_picture exit\n");
// }

#define HTTP_RESP_CONTENT_LEN (256)
int bkwl_http_download_file(const char *uri)
{
	int ret;
	httpclient_t httpclient;
	httpclient_data_t httpclient_data;
	char http_content[HTTP_RESP_CONTENT_LEN];

	tprintf("twh bkwl_http_download_file entry\n");
	if (!uri)
	{
		ret = BK_FAIL;
		CLI_LOGI("uri is NULL\r\n");

		return ret;
	}

	os_memset(&httpclient, 0, sizeof(httpclient_t));
	os_memset(&httpclient_data, 0, sizeof(httpclient_data));
	os_memset(&http_content, 0, sizeof(HTTP_RESP_CONTENT_LEN));
	httpclient.header = "Accept: text/xml,text/html,\r\n";
	httpclient_data.response_buf = http_content;
	httpclient_data.response_content_len = HTTP_RESP_CONTENT_LEN;
	ret = httpclient_common(&httpclient,
							uri,
							80, /*port*/
							NULL,
							HTTPCLIENT_GET,
							180000,
							&httpclient_data);

	if (0 != ret)
	{
		tprintf("request epoch time from remote server failed.ret:%d\r\n", ret);
	}
	else
	{
		tprintf("sucess.\r\n");
		tprintf("data len=%d:\n%s\n", httpclient_data.retrieve_len, httpclient_data.response_buf);
	}

	// typedef struct {
	// 	bool is_more; /**< Indicates if more data needs to be retrieved. */
	// 	bool is_chunked; /**< Response data is encoded in portions/chunks.*/
	// 	int retrieve_len; /**< Content length to be retrieved. */
	// 	uint32_t response_content_len; /**< Response content length. */
	// 	uint32_t post_buf_len; /**< Post data length. */
	// 	uint32_t response_buf_len; /**< Response buffer length. */
	// 	char *post_content_type; /**< Content type of the post data. */
	// 	char *post_buf; /**< User data to be posted. */
	// 	char *response_buf; /**< Buffer to store the response data. */
	// } httpclient_data_t;

	return ret;
}

char *bkwl_http_get(const char *uri)
{
	char *ret = NULL;
	tprintf("twh bkwl_http_get uri=%s\n", uri);
	struct webclient_session *session = NULL;
	int bytes_read = 0;
	char *buffer = (char *)malloc(2048);
	memset(buffer, 0, 2048);
	session = webclient_session_create(1024);
	if (webclient_get(session, uri) != 200)
	{
		tprintf("#### bkwl_http_get  error!\n\n\n");
	}
	int content_pos = 0;
	/* 获取接收的响应数据长度 */
	int content_length = webclient_content_length_get(session);
	if (content_length > 0)
	{
		ret = (char *)malloc(content_length + 1);
		os_memset(ret, 0, content_length + 1);
		/* 循环接收响应数据直到数据接收完毕 */
		do
		{
			bytes_read = webclient_read(session, buffer, 1024);
			if (bytes_read <= 0)
			{
				break;
			}
			// tprintf("\n bkwl_http_get get data:\n");
			// /* 打印响应数据 */
			// for (index = 0; index < bytes_read; index++)
			// {
			// 	tprintf("%c", buffer[index]);
			// }
			os_memcpy(ret + content_pos, buffer, bytes_read);
			content_pos += bytes_read;
		} while (content_pos < content_length);
		// tprintf("\n\n");
	}
	free(buffer);
	webclient_close(session);
	tprintf(" bkwl_http_get data:\n\n%s\n\n", ret);
	return ret;
}

int bkwl_http_post(const char *uri, uint8_t *post_data, uint32_t data_len)
{
	return bkwl_http_post_base(uri, post_data, data_len, 0);
}

// int bkwl_http_post_formdata(const char *uri, uint8_t *post_data, uint32_t data_len)
// {
// 	return bkwl_http_post_filedata(uri, post_data, data_len);
// }
#define RT_NULL NULL
#define RCV_BUF_SIZE 256 * 1
#define SEND_HEADER_SIZE 256
int bkwl_http_post_base(const char *uri, uint8_t *post_data, uint32_t data_len, uint8_t data_type)
{
	//	int ret = 0;

	tprintf("twh bkwl_http_post 1\n");
	tprintf("twh bkwl_http_post entry\n");
	tprintf("twh bkwl_http_post uri=%s\n", uri);
	tprintf("twh bkwl_http_post data=%s\n", post_data);

	char rep_data[RCV_BUF_SIZE] = {0};
	// data_len = sizeof(post_data);
	struct webclient_session *session = RT_NULL;
	unsigned char *buffer = RT_NULL;
	int ret = 0;
	int bytes_read, resp_status;

	tprintf("twh bkwl_http_post 2\n");
	buffer = (unsigned char *)web_malloc(RCV_BUF_SIZE);
	if (buffer == RT_NULL)
	{
		tprintf("no memory for receive response buffer.\n");
		ret = -5;
		goto __exit;
	}

	tprintf("twh bkwl_http_post 3\n");
	/* create webclient session and set header response size */
	session = webclient_session_create(SEND_HEADER_SIZE);
	if (session == RT_NULL)
	{
		ret = -5;
		tprintf("webclient_session_create fail.\n");
		goto __exit;
	}
	tprintf("twh bkwl_http_post 4\n");
	char version_buf[32] = "7256000";

	/* build header for upload */
	webclient_header_fields_add(session, "Content-Length: %d\r\n", data_len);
	if (data_type == 0)
		webclient_header_fields_add(session, "Content-Type: application/json\r\n");
	else
		webclient_header_fields_add(session, "Content-Type: application/x-www-form-urlencoded\r\n");
	webclient_header_fields_add(session, "%s\r\n", version_buf);

	tprintf("twh bkwl_http_post 5\n");
	/* send POST request by default header */
	if ((resp_status = webclient_post(session, uri, post_data, data_len)) != 200)
	{
		tprintf("webclient POST request failed, response(%d) error.\n", resp_status);
		ret = -1;
		goto __exit;
	}

	tprintf("twh bkwl_http_post  webclient post response data: \n");
	do
	{
		bytes_read = webclient_read(session, buffer, RCV_BUF_SIZE);
		if (bytes_read <= 0)
		{
			break;
		}
		strncat(rep_data, (char *)buffer, bytes_read);
	} while (1);

	tprintf("twh bkwl_http_post rep_data:\n %s\n", rep_data);

__exit:
	tprintf("twh bkwl_http_post 7\n");
	if (session)
	{
		webclient_close(session);
	}

	tprintf("twh bkwl_http_post 8\n");
	if (buffer)
	{
		tprintf(" bkwl_http_post data:\n\n%s\n\n", buffer);
		web_free(buffer);
	}

	tprintf(" bkwl_http_post  exit\n");

	return ret;
}

#define UPLOAD_DEVICE_NAME "Content-Disposition: form-data; name=\"device_name\"\r\n\r\n"
#define UPLOAD_DEVICE_IMAGE "Content-Disposition: form-data; name=\"upload\"; filename=\"bkwl%lld.jpeg\"\r\nContent-Type: image/jpeg\r\n\r\n"
int bkwl_http_post_filedata(const char *uri, uint8_t *post_data, uint32_t data_len, char *device_name)
{
	//	int ret = 0;

	tprintf("twh bkwl_http_post_filedata entry\n");
	tprintf("twh bkwl_http_post_filedata uri=%s\n", uri);
	tprintf("twh bkwl_http_post_filedata device_name=%s\n", device_name);
	tprintf("twh bkwl_http_post_filedata data_len=%d\n", data_len);
	tprintf("twh bkwl_http_post_filedata data=%s\n", post_data);

	char rep_data[RCV_BUF_SIZE] = {0};
	// data_len = sizeof(post_data);
	struct webclient_session *session = RT_NULL;
	unsigned char *buffer = RT_NULL;
	int ret = 0;
	int bytes_read, resp_status;

	tprintf("twh bkwl_http_post 2\n");
	buffer = (unsigned char *)web_malloc(RCV_BUF_SIZE);
	if (buffer == RT_NULL)
	{
		tprintf("no memory for receive response buffer.\n");
		ret = -5;
		goto __exit;
	}

	tprintf("twh bkwl_http_post 3\n");
	/* create webclient session and set header response size */
	session = webclient_session_create(SEND_HEADER_SIZE);
	if (session == RT_NULL)
	{
		ret = -5;
		tprintf("webclient_session_create fail.\n");
		goto __exit;
	}
	tprintf("twh bkwl_http_post 4\n");
	char version_buf[32] = "7256000";

	long long int timestamp;
	struct timeval tv;
	bk_rtc_gettimeofday(&tv, NULL);
	tprintf("twh bkwl_http_post time=%lld\n", tv.tv_sec);
	timestamp = (long long int)tv.tv_sec * 1000 + tv.tv_usec;
	char startmsg_buf[100] = {0};
	char endmsg_buf[100] = {0};
	char http_boundary[64] = {0};
	char upload_device_name_buf[100] = {0};
	char upload_device_image_buf[128] = {0};
	int start_boundary_len = 0;
	int end_boundary_len = 0;
	int device_name_len = strlen(device_name);
	int upload_device_name_len = 0;
	int upload_device_image_len = 0;
	int content_length;

	tprintf("device_name_len=%d, device_name=%s\r\n", device_name_len, device_name);
	// 1. 获取http_boundary
	sprintf(http_boundary, "--------------------------%lld", timestamp);
	// 2. start boundary
	start_boundary_len = sprintf(startmsg_buf, "\r\n--%s\r\n", http_boundary);
	// 3. end boundart
	end_boundary_len = sprintf(endmsg_buf, "\r\n--%s--\r\n", http_boundary);
	// 4.
	// #define UPLOAD_DEVICE_NAME "Content-Disposition: form-data; name=\"device_name\"\r\n%s\r\n"
	// #define UPLOAD_DEVICE_IMAGE "Content-Disposition:form-data;name=\"upload\";filename=\"bkwl_%lld.jpeg\"\r\n"
	upload_device_image_len = sprintf(upload_device_image_buf, UPLOAD_DEVICE_IMAGE, timestamp);
	upload_device_name_len = sprintf(upload_device_name_buf, UPLOAD_DEVICE_NAME);
	content_length = start_boundary_len + upload_device_name_len + device_name_len + start_boundary_len + upload_device_image_len + data_len + end_boundary_len;
	/* build header for upload */

	char tmp_buf[100] = {0};
	sprintf(tmp_buf, "Content-Length: %d\r\n", content_length);
	tprintf("%s\n", tmp_buf);
	// webclient_header_fields_add(session, "Content-Length: %d\r\n", content_length);
	webclient_header_fields_add(session, tmp_buf);
	sprintf(tmp_buf, "Content-Type: multipart/form-data; boundary=%s\r\n", http_boundary);
	// tprintf("%s\n", tmp_buf);
	webclient_header_fields_add(session, tmp_buf);
	webclient_header_fields_add(session, "%s\r\n", version_buf);
	uint8_t *post_send_data = (uint8_t *)malloc(content_length + 30);
	memset(post_send_data, 0, content_length + 30);
	memcpy(post_send_data, startmsg_buf, start_boundary_len);									 // 开始
	memcpy(post_send_data + start_boundary_len, upload_device_name_buf, upload_device_name_len); // 字段信息
	// tprintf("twh bkwl_http_post  name label:\n%s\n", post_send_data);
	memcpy(post_send_data + start_boundary_len + upload_device_name_len, device_name, device_name_len); // 数据

	// tprintf("twh bkwl_http_post device name:\n%s\n", post_send_data);

	memcpy(post_send_data + start_boundary_len + upload_device_name_len + device_name_len, startmsg_buf, start_boundary_len);									   // 开始
	memcpy(post_send_data + start_boundary_len + upload_device_name_len + device_name_len + start_boundary_len, upload_device_image_buf, upload_device_image_len); // 字段信息

	memcpy(post_send_data + start_boundary_len + upload_device_name_len + device_name_len + start_boundary_len + upload_device_image_len, post_data, data_len);						// 数据
	memcpy(post_send_data + start_boundary_len + upload_device_name_len + device_name_len + start_boundary_len + upload_device_image_len + data_len, endmsg_buf, end_boundary_len); // 数据

	tprintf("twh bkwl_http_post data:\n%s\n", post_send_data);

	if ((resp_status = webclient_post(session, uri, post_send_data, content_length)) != 200)
	{
		tprintf("webclient POST request failed, response(%d) error.\n", resp_status);
		ret = -1;
		goto __exit;
	}

	tprintf("twh bkwl_http_post  webclient post response data: \n");
	do
	{
		bytes_read = webclient_read(session, buffer, RCV_BUF_SIZE);
		if (bytes_read <= 0)
		{
			break;
		}
		strncat(rep_data, (char *)buffer, bytes_read);
	} while (1);

	tprintf("twh bkwl_http_post rep_data:\n %s\n", rep_data);

__exit:
	tprintf("twh bkwl_http_post 7\n");
	if (session)
	{
		webclient_close(session);
	}

	tprintf("twh bkwl_http_post 8\n");
	if (buffer)
	{
		web_free(buffer);
	}

	tprintf(" bkwl_http_post  exit\n");

	return ret;
}

// long long int timestamp;
//         struct timeval tv;
//         gettimeofday(&tv,NULL);
//         timestamp = (long long int)tv.tv_sec * 1000 + tv.tv_usec;
//         //1. 获取http_boundary
//         sprintf(http_boundary,"----------------------------%lld",timestamp);
//         //2. start boundary
//         startboundarylen = sprintf(startmsg, "--%s\r\n",http_boundary);
//         //3. end boundart
//         endboundarylen = sprintf(endmsg, "\r\n--%s--\r\n",http_boundary);
//         //4.
//         int requelen = sprintf(request, UPLOAD_REQUEST, httpparam.picparm.picname);
//         int Content_Length = requelen + startboundarylen  +  httpparam.picparm.picsize + endboundarylen;
//         int headerlen = sprintf(header, HTTP_POST_PIC_HEAD, httpparam.url, httpparam.host, http_boundary, Content_Length);
//         int tolsize = Content_Length + strlen(HTTP_POST_PIC_HEAD) + 256; //加256防止溢出

//         memcpy(httppack, header, headerlen);
//         memcpy(httppack+headerlen, startmsg, startboundarylen);
//         memcpy(httppack+headerlen+startboundarylen, request, requelen);
//         memcpy(httppack+headerlen+startboundarylen+requelen, httpparam.content, httpparam.picparm.picsize);
//         memcpy(httppack+headerlen+startboundarylen+requelen+httpparam.picparm.picsize, endmsg, endboundarylen);

////////////////
// POST /api/wx/upload/upload.php?upload=aaa HTTP/1.1
// User-Agent: PostmanRuntime/7.39.0
// Accept: */*
// Postman-Token: 5bba1df9-5747-4ddf-8d02-088a4820650c
// Host: m.yo-jia.cn
// Accept-Encoding: gzip, deflate, br
// Connection: keep-alive
// Content-Type: multipart/form-data; boundary=--------------------------167546910742878758570297
// Content-Length: 129592

// ----------------------------167546910742878758570297
// Content-Disposition: form-data; name="device_name"
// D_bFbWajDKqfx4C4am
// ----------------------------167546910742878758570297
// Content-Disposition: form-data; name="upload"; filename="chrome_100_percent.pak"
// <chrome_100_percent.pak>
// ----------------------------167546910742878758570297--

// HTTP/1.1 200 OK
// Server: nginx/1.20.1
// Date: Thu, 27 Jun 2024 10:01:38 GMT
// Content-Type: text/plain;charset=UTF-8
// Content-Length: 139
// Connection: keep-alive
// Strict-Transport-Security: max-age=31536000; includeSubDomains

// {"msg":"上传成功","file_path":"https://yojia-1323378402.cos.ap-guangzhou.myqcloud.com/files/2024-06-27/20240627180138657.pak","code":2}
